import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Card, Slider, Switch, InputNumber, Row, Col, Typography, Space, Divider, ConfigProvider, Button, message } from 'antd';
import { RotateLeftOutlined, RotateRightOutlined, SwapOutlined, VerticalAlignTopOutlined } from '@ant-design/icons';
import { theme } from 'antd';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { useSegmentForm, useDebouncedSave } from './hooks';
import { ClipSettings as ClipSettingsType } from './types';

const { Title, Text } = Typography;

// 暗黑主题配置
const darkTheme = {
    algorithm: theme.darkAlgorithm,
    token: {
        colorPrimary: '#715bb8',
        colorBgContainer: '#2a2a2a',
        colorBgElevated: '#2a2a2a',
        colorText: '#ffffff',
        colorTextSecondary: 'rgba(255, 255, 255, 0.7)',
        colorBorder: '#434343',
        colorBorderSecondary: '#434343',
        borderRadius: 6,
        colorFillSecondary: '#434343',
    },
    components: {
        Card: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextHeading: '#ffffff',
        },
        Slider: {
            trackBg: '#434343',
            trackHoverBg: '#434343',
            handleColor: '#715bb8',
            handleActiveColor: '#715bb8',
            railBg: '#434343',
            railHoverBg: '#434343',
        },
        InputNumber: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextPlaceholder: 'rgba(255, 255, 255, 0.5)',
            colorPrimaryHover: '#715bb8',
            colorPrimary: '#715bb8',
        },
        Switch: {
            colorPrimary: '#715bb8',
            colorPrimaryHover: '#715bb8',
        },
        Divider: {
            colorSplit: '#434343',
        },
        Button: {
            colorBgContainer: 'transparent',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextDisabled: 'rgba(255, 255, 255, 0.3)',
            colorBgTextHover: 'rgba(113, 91, 184, 0.1)',
            colorBorderHover: '#715bb8',
        },
    },
};

interface ClipSettingsProps {
    disabled?: boolean;
    // 用于从 Redux 获取片段数据
    trackId?: string;
    segmentId?: string;
    // 用于防抖保存的参数
    draftId?: string;
}

const ClipSettingsComponent: React.FC<ClipSettingsProps> = ({ disabled = false, trackId, segmentId, draftId }) => {
    // 使用新的 store hook
    const { setCurrentSegmentInfo, updateSegmentConfig } = useSegmentForm();
    const debouncedSave = useDebouncedSave(800);

    // 防抖定时器引用
    const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

    // 从 Redux 获取基础数据
    const scriptData = useSelector((state: RootState) => state.drafts.scriptData);

    // 使用 useMemo 优化片段数据获取
    const segment = useMemo(() => {
        if (!trackId || !segmentId || !scriptData?.tracks) return null;

        const track = scriptData.tracks.find((track: any) => track.id === trackId);
        if (!track || !track.segments) return null;

        return track.segments.find((segment: any) => segment.id === segmentId) || null;
    }, [trackId, segmentId, scriptData?.tracks]);

    // 使用 useMemo 优化轨道数据获取
    const currentTrack = useMemo(() => {
        if (!scriptData?.tracks) return null;
        return scriptData.tracks.find((track: any) => track.id === trackId) || null;
    }, [trackId, scriptData?.tracks]);

    // 默认的 clip 设置
    const defaultClipSettings: ClipSettingsType = {
        alpha: 1.0,
        flip: {
            horizontal: false,
            vertical: false,
        },
        rotation: 0.0,
        scale: {
            x: 1.0,
            y: 1.0,
        },
        transform: {
            x: 0.0,
            y: 0.0,
        },
    };

    // 从片段数据中获取 clip 设置，如果没有则使用默认值
    const initialClipSettings = segment?.clip || defaultClipSettings;
    const [settings, setSettings] = useState<ClipSettingsType>(initialClipSettings);

    // 设置当前片段信息到 store
    useEffect(() => {
        if (trackId && segmentId && draftId && segment) {
            setCurrentSegmentInfo({
                draftId,
                trackId,
                segmentId,
                type: currentTrack?.type as any,
                materialId: segment.material_id,
                start: segment.target_timerange?.start || 0,
                duration: segment.target_timerange?.duration || 0,
            });
        }
    }, [trackId, segmentId, draftId, segment, currentTrack, setCurrentSegmentInfo]);

    // 当片段数据变化时，更新内部状态
    useEffect(() => {
        if (segment?.clip) {
            setSettings(segment.clip);
        }
    }, [segment?.clip]);

    // 组件卸载时清理定时器
    useEffect(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);

    // 防抖更新设置 - 用于连续调整的操作（如滑块拖拽）
    // 策略：立即更新UI状态，延迟300ms后更新store和保存
    const debouncedUpdateSettings = useCallback(
        (newSettings: Partial<ClipSettingsType>) => {
            // 清除之前的定时器
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }

            // 立即更新本地状态（用于UI响应）
            const updatedSettings = { ...settings, ...newSettings };
            setSettings(updatedSettings);

            // 设置防抖定时器
            debounceTimerRef.current = setTimeout(() => {
                // 更新到 store
                updateSegmentConfig({ clip: updatedSettings });
                // 触发防抖保存
                debouncedSave({ clip: updatedSettings });
            }, 300); // 300ms 防抖延迟
        },
        [settings, updateSegmentConfig, debouncedSave]
    );

    // 立即更新设置 - 用于离散操作（如按钮点击、开关切换）
    // 策略：立即更新UI状态、store和保存
    const immediateUpdateSettings = useCallback(
        (newSettings: Partial<ClipSettingsType>) => {
            const updatedSettings = { ...settings, ...newSettings };
            setSettings(updatedSettings);
            updateSegmentConfig({ clip: updatedSettings });
            debouncedSave({ clip: updatedSettings });
        },
        [settings, updateSegmentConfig, debouncedSave]
    );

    // 处理透明度变化（防抖）
    const handleAlphaChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({ alpha: value / 100 });
        },
        [debouncedUpdateSettings]
    );

    // 处理旋转角度变化（防抖）
    const handleRotationChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({ rotation: value });
        },
        [debouncedUpdateSettings]
    );

    // 处理水平翻转（立即更新）
    const handleHorizontalFlipChange = useCallback(
        (checked: boolean) => {
            immediateUpdateSettings({
                flip: {
                    ...settings.flip,
                    horizontal: checked,
                },
            });
        },
        [settings.flip, immediateUpdateSettings]
    );

    // 处理垂直翻转（立即更新）
    const handleVerticalFlipChange = useCallback(
        (checked: boolean) => {
            immediateUpdateSettings({
                flip: {
                    ...settings.flip,
                    vertical: checked,
                },
            });
        },
        [settings.flip, immediateUpdateSettings]
    );

    // 处理缩放变化（防抖）
    const handleScaleXChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({
                scale: {
                    ...settings.scale,
                    x: value / 100,
                },
            });
        },
        [settings.scale, debouncedUpdateSettings]
    );

    const handleScaleYChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({
                scale: {
                    ...settings.scale,
                    y: value / 100,
                },
            });
        },
        [settings.scale, debouncedUpdateSettings]
    );

    // 处理位移变化（防抖）
    const handleTransformXChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({
                transform: {
                    ...settings.transform,
                    x: value,
                },
            });
        },
        [settings.transform, debouncedUpdateSettings]
    );

    const handleTransformYChange = useCallback(
        (value: number) => {
            debouncedUpdateSettings({
                transform: {
                    ...settings.transform,
                    y: value,
                },
            });
        },
        [settings.transform, debouncedUpdateSettings]
    );

    // 快速旋转按钮（立即更新）
    const handleQuickRotate = useCallback(
        (angle: number) => {
            const newRotation = (settings.rotation + angle) % 360;
            immediateUpdateSettings({ rotation: newRotation });
        },
        [settings.rotation, immediateUpdateSettings]
    );

    // 位置按钮处理函数
    const handlePositionClick = useCallback(
        (position: string) => {
            switch (position) {
                case 'bottom-right':
                    message.success('右下角');
                    immediateUpdateSettings({
                        transform: {
                            x: 4,
                            y: 0.1,
                        },
                    });
                    break;
                case 'top-left':
                    message.success('左上角');
                    immediateUpdateSettings({
                        transform: {
                            x: -4.5,
                            y: -0.2,
                        },
                    });
                    break;
                case 'top-right':
                    message.success('右上角');
                    immediateUpdateSettings({
                        transform: {
                            x: 4,
                            y: -0.2,
                        },
                    });
                    break;
                case 'bottom-left':
                    message.success('左下角');
                    immediateUpdateSettings({
                        transform: {
                            x: -4.5,
                            y: 0.1,
                        },
                    });
                    break;
            }
        },
        [immediateUpdateSettings]
    );

    // 缩放按钮处理函数
    const handleScaleClick = useCallback(
        (scaleType: string) => {
            switch (scaleType) {
                case 'zoom-in':
                    message.success('放大1倍');
                    // 基于当前状态放大10%（1.1倍）
                    immediateUpdateSettings({
                        scale: {
                            x: (settings.scale.x || 1.0) * 1.1,
                            y: (settings.scale.y || 1.0) * 1.1,
                        },
                    });
                    break;
                case 'zoom-out':
                    message.success('缩小1倍');
                    // 基于当前状态缩小10%（0.9倍）
                    immediateUpdateSettings({
                        scale: {
                            x: (settings.scale.x || 1.0) * 0.9,
                            y: (settings.scale.y || 1.0) * 0.9,
                        },
                    });
                    break;
            }
        },
        [settings.scale, immediateUpdateSettings]
    );

    return (
        <ConfigProvider theme={darkTheme}>
            <div style={{ width: '100%' }}>
                <Card size="small" title="片段变换设置">
                    <Space direction="vertical" size="small" style={{ width: '100%' }}>
                        {/* 位移设置 */}
                        <div>
                            <Title level={5} style={{ color: '#ffffff', marginBottom: '4px', fontSize: '13px' }}>
                                位移
                            </Title>

                            {/* 位置按钮 */}
                            <div style={{ marginBottom: '12px' }}>
                                <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '8px' }}>快速定位</Text>
                                <Row gutter={8}>
                                    <Col span={6}>
                                        <Button size="small" style={{ width: '100%' }} onClick={() => handlePositionClick('top-left')} disabled={disabled} title="左上角">
                                            左上
                                        </Button>
                                    </Col>
                                    <Col span={6}>
                                        <Button size="small" style={{ width: '100%' }} onClick={() => handlePositionClick('top-right')} disabled={disabled} title="右上角">
                                            右上
                                        </Button>
                                    </Col>
                                    <Col span={6}>
                                        <Button size="small" style={{ width: '100%' }} onClick={() => handlePositionClick('bottom-left')} disabled={disabled} title="左下角">
                                            左下
                                        </Button>
                                    </Col>
                                    <Col span={6}>
                                        <Button size="small" style={{ width: '100%' }} onClick={() => handlePositionClick('bottom-right')} disabled={disabled} title="右下角">
                                            右下
                                        </Button>
                                    </Col>
                                </Row>
                            </div>

                            <Row gutter={12} style={{ marginBottom: '8px' }}>
                                <Col span={12}>
                                    <div style={{ marginBottom: '8px' }}>
                                        <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '8px' }}>水平位移</Text>
                                        <Row align="middle" gutter={8}>
                                            <Col span={16}>
                                                <Slider min={-10} max={10} step={0.1} value={settings.transform.x} onChange={handleTransformXChange} disabled={disabled} />
                                            </Col>
                                            <Col span={8}>
                                                <InputNumber
                                                    min={-2}
                                                    max={2}
                                                    step={0.1}
                                                    value={settings.transform.x}
                                                    onChange={(value) => handleTransformXChange(typeof value === 'number' ? value : 0)}
                                                    disabled={disabled}
                                                    size="small"
                                                    style={{ width: '100%' }}
                                                />
                                            </Col>
                                        </Row>
                                    </div>
                                </Col>
                                <Col span={12}>
                                    <div style={{ marginBottom: '8px' }}>
                                        <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '8px' }}>垂直位移</Text>
                                        <Row align="middle" gutter={8}>
                                            <Col span={16}>
                                                <Slider min={-10} max={5} step={0.01} value={settings.transform.y} onChange={handleTransformYChange} disabled={disabled} />
                                            </Col>
                                            <Col span={8}>
                                                <InputNumber
                                                    min={-2}
                                                    max={2}
                                                    step={0.1}
                                                    value={settings.transform.y}
                                                    onChange={(value) => handleTransformYChange(typeof value === 'number' ? value : 0)}
                                                    disabled={disabled}
                                                    size="small"
                                                    style={{ width: '100%' }}
                                                />
                                            </Col>
                                        </Row>
                                    </div>
                                </Col>
                            </Row>
                        </div>

                        <Divider style={{ backgroundColor: '#434343', margin: '6px 0' }} />

                        {/* 缩放设置 */}
                        <div>
                            <Title level={5} style={{ color: '#ffffff', marginBottom: '4px', fontSize: '13px' }}>
                                缩放
                            </Title>

                            {/* 快速缩放按钮 */}
                            <div style={{ marginBottom: '12px' }}>
                                <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '8px' }}>快速缩放</Text>
                                <Row gutter={8}>
                                    <Col span={12}>
                                        <Button size="small" style={{ width: '100%' }} onClick={() => handleScaleClick('zoom-out')} disabled={disabled} title="缩小1倍">
                                            缩小1倍
                                        </Button>
                                    </Col>
                                    <Col span={12}>
                                        <Button size="small" style={{ width: '100%' }} onClick={() => handleScaleClick('zoom-in')} disabled={disabled} title="放大1倍">
                                            放大1倍
                                        </Button>
                                    </Col>
                                </Row>
                            </div>

                            <Row gutter={12} style={{ marginBottom: '8px' }}>
                                <Col span={12}>
                                    <div style={{ marginBottom: '8px' }}>
                                        <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '8px' }}>水平缩放</Text>
                                        <Row align="middle" gutter={8}>
                                            <Col span={16}>
                                                <Slider min={10} max={500} value={Math.round(settings.scale.x * 100)} onChange={handleScaleXChange} disabled={disabled} />
                                            </Col>
                                            <Col span={8}>
                                                <InputNumber
                                                    min={10}
                                                    max={500}
                                                    value={Math.round(settings.scale.x * 100)}
                                                    onChange={(value) => handleScaleXChange(typeof value === 'number' ? value : 100)}
                                                    disabled={disabled}
                                                    size="small"
                                                    style={{ width: '100%' }}
                                                    addonAfter="%"
                                                />
                                            </Col>
                                        </Row>
                                    </div>
                                </Col>
                                <Col span={12}>
                                    <div style={{ marginBottom: '8px' }}>
                                        <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '8px' }}>垂直缩放</Text>
                                        <Row align="middle" gutter={8}>
                                            <Col span={16}>
                                                <Slider min={10} max={500} value={Math.round(settings.scale.y * 100)} onChange={handleScaleYChange} disabled={disabled} />
                                            </Col>
                                            <Col span={8}>
                                                <InputNumber
                                                    min={10}
                                                    max={500}
                                                    value={Math.round(settings.scale.y * 100)}
                                                    onChange={(value) => handleScaleYChange(typeof value === 'number' ? value : 100)}
                                                    disabled={disabled}
                                                    size="small"
                                                    style={{ width: '100%' }}
                                                    addonAfter="%"
                                                />
                                            </Col>
                                        </Row>
                                    </div>
                                </Col>
                            </Row>
                        </div>

                        <Divider style={{ backgroundColor: '#434343', margin: '6px 0' }} />

                        {/* 透明度设置 */}
                        <div>
                            <Title level={5} style={{ color: '#ffffff', marginBottom: '4px', fontSize: '13px' }}>
                                透明度
                            </Title>
                            <Row align="middle" gutter={8}>
                                <Col span={4}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>透明</Text>
                                </Col>
                                <Col span={16}>
                                    <Slider min={0} max={100} value={Math.round(settings.alpha * 100)} onChange={handleAlphaChange} disabled={disabled} />
                                </Col>
                                <Col span={4}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>不透明</Text>
                                </Col>
                            </Row>
                            <div style={{ textAlign: 'center', marginTop: '2px' }}>
                                <Text style={{ color: '#ffffff', fontSize: '12px' }}>{Math.round(settings.alpha * 100)}%</Text>
                            </div>
                        </div>

                        <Divider style={{ backgroundColor: '#434343', margin: '6px 0' }} />

                        {/* 旋转设置 */}
                        <div>
                            <Title level={5} style={{ color: '#ffffff', marginBottom: '4px', fontSize: '13px' }}>
                                旋转
                            </Title>
                            <Row align="middle" gutter={8}>
                                <Col span={4}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>-180°</Text>
                                </Col>
                                <Col span={12}>
                                    <Slider min={-180} max={180} value={settings.rotation} onChange={handleRotationChange} disabled={disabled} />
                                </Col>
                                <Col span={4}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>180°</Text>
                                </Col>
                                <Col span={4}>
                                    <Space>
                                        <Button size="small" icon={<RotateLeftOutlined />} onClick={() => handleQuickRotate(-90)} disabled={disabled} title="逆时针旋转90°" />
                                        <Button size="small" icon={<RotateRightOutlined />} onClick={() => handleQuickRotate(90)} disabled={disabled} title="顺时针旋转90°" />
                                    </Space>
                                </Col>
                            </Row>
                            <div style={{ textAlign: 'center', marginTop: '2px' }}>
                                <Text style={{ color: '#ffffff', fontSize: '12px' }}>{settings.rotation.toFixed(1)}°</Text>
                            </div>
                        </div>

                        <Divider style={{ backgroundColor: '#434343', margin: '6px 0' }} />

                        {/* 翻转设置 */}
                        <div>
                            <Title level={5} style={{ color: '#ffffff', marginBottom: '4px', fontSize: '13px' }}>
                                翻转
                            </Title>
                            <Row gutter={12} style={{ marginBottom: '8px' }}>
                                <Col span={12}>
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                        <Space>
                                            <SwapOutlined style={{ color: '#ffffff' }} />
                                            <Text style={{ color: '#ffffff', fontSize: '12px' }}>水平翻转</Text>
                                        </Space>
                                        <Switch checked={settings.flip.horizontal} onChange={handleHorizontalFlipChange} disabled={disabled} size="small" />
                                    </div>
                                </Col>
                                <Col span={12}>
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                        <Space>
                                            <VerticalAlignTopOutlined style={{ color: '#ffffff' }} />
                                            <Text style={{ color: '#ffffff', fontSize: '12px' }}>垂直翻转</Text>
                                        </Space>
                                        <Switch checked={settings.flip.vertical} onChange={handleVerticalFlipChange} disabled={disabled} size="small" />
                                    </div>
                                </Col>
                            </Row>
                        </div>
                    </Space>
                </Card>
            </div>
        </ConfigProvider>
    );
};

export default ClipSettingsComponent;
